<template>
	<div class="page-wrapper">
		<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataLists()">
			<el-form-item>
				<el-input v-model="state.queryForm.search" placeholder="输入产品名称/属性名称搜索" clearable style="width: 300px;"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button @click="getDataLists()" type="primary">查询</el-button>
			</el-form-item>
			<el-form-item>
				<el-button @click="clearForm()">重置</el-button>
			</el-form-item>
			<el-form-item>
				<el-button @click="exportData()" type="success" v-if="hasRule('admin/inventory/inventory/export')">导出</el-button>
			</el-form-item>
		</el-form>
        <div class="mb10 flex">
            <div class="mr20 font16 bold">库存总数量：{{ totalNum }}</div>
            <div class="mr20 font16 bold">库存总货值：{{ totalPrice }}</div>
        </div>
		<el-table v-loading="state.dataListLoading" :data="dataList" border style="width: 100%" width="100%" height="100%">
            <!-- @selection-change="selectionChangeHandle"  -->
			<!-- <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column> -->
			<el-table-column prop="created_at" label="创建时间" header-align="center" align="center" width="180"></el-table-column>
			<el-table-column prop="name" label="产品名称" header-align="center" align="center">
                <template #default="scope">
					<div class="w100 flex flexL flexC">
                        <div class="mr10 flex flexL" v-if="scope.row.images.length">
                            <el-image
                                style="width: 30px; height: 30px;border-radius: 2px;"
                                :src="scope.row.images[0]"
                                preview-teleported
                                :preview-src-list="scope.row.images"
                                :initial-index="0"
                                fit="cover"
                                />
                        </div>
                        <div>{{scope.row.name}}</div>
                    </div>
				</template>
            </el-table-column>
			<el-table-column prop="type.name" label="产品类型" header-align="center" align="center"></el-table-column>
			<el-table-column prop="attr" label="产品属性" header-align="center" align="center">
                <template #default="scope">
					<span>{{scope.row.attr_name_fill}}-{{scope.row.attr_name}}</span>
				</template>
            </el-table-column>
			<el-table-column prop="inventory" label="库存数量" header-align="center" align="center"></el-table-column>
			<el-table-column prop="cost_price" label="单价" header-align="center" align="center"></el-table-column>
			<el-table-column prop="cost_total" label="库存货值" header-align="center" align="center"></el-table-column>
			<el-table-column prop="warning" label="库存预警值" header-align="center" align="center"></el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="350">
				<template #default="scope">
					<el-button type="primary" link @click="handleChange(scope.row.id)" v-if="hasRule('admin/inventory/inventory/change')">调整预警值</el-button>
					<el-button type="success" link @click="handleCheck(scope.row, 1, true)" v-if="hasRule('admin/inventory/inventory/in')">查看入库记录</el-button>
					<el-button type="success" link @click="handleCheck(scope.row, 2, true)" v-if="hasRule('admin/inventory/inventory/out')">查看出库记录</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.page"
			:page-sizes="state.pageSizes"
			:page-size="state.per_page"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>
        <el-dialog v-model="visible" :title="title" width="1200px" center :destroy-on-close="true">
           <div class="w100">
            <!-- <div class="textR mb10">{{ totalText }}</div> -->
            <div class="flex mb10 flexL">
                <div v-if="itemType==1">入库时间：</div>
                <div v-if="itemType==2">出库时间：</div>
                <div class="mr10">
                    <el-date-picker :shortcuts="SHORTCUTS" v-model="record_time" style="width:240px;" @change="dataChange" type="daterange" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" clearable />
                </div>
                <div class="mr10" v-if="itemType==2">
                    <el-select v-model="search.customer_name" placeholder="选择客户" clearable style="width: 100%;">
                        <el-option v-for="i in customerList" :key="i.value" :label="i.label" :value="i.label" />
                    </el-select>
                </div>
                <div class="mr10" v-if="itemType==2">
                    <el-select v-model="search.department_name" placeholder="选择部门" clearable style="width: 100%;">
                        <el-option v-for="i in departmentList" :key="i.value" :label="i.label" :value="i.label" />
                    </el-select>
                </div>
                <div class="mr10" v-if="itemType==1">
                    <el-select v-model="search.supplier_name" placeholder="选择供应商" clearable style="width: 100%;">
                        <el-option v-for="i in supplierList" :key="i.value" :label="i.label" :value="i.value" />
                    </el-select>
                </div>
                <div class="mr10">
                    <el-input v-model="search.batch_no" placeholder="输入批次号搜索" clearable style="width: 180px;"></el-input>
                </div>
                <div>
                    <el-button type="primary" @click="searchHandle()">搜索</el-button>
                </div>
            </div>
            <div class="mb10">
                表格当前页数据出入库数量汇总(不含分页)：<span class="bold">{{ totalNumPro }}</span>
            </div>
            <el-scrollbar height="600px">
                <el-table :data="itemList" border style="width: 100%" width="100%" height="100%" v-if="itemType==1">
                    <el-table-column prop="order_sn" label="入库单号" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="in_time" label="入库时间" header-align="center" align="center" width="100"></el-table-column>
                    <el-table-column prop="in_type" label="入库类型" header-align="center" align="center">
                        <template #default="scope">
                            <span v-if="scope.row.in_type == 1">产品采购入库</span>
                            <span v-if="scope.row.in_type == 2">材料采购入库</span>
                            <span v-if="scope.row.in_type == 3">退货入库</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="batch_no" label="批次号" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="quantity" label="入库数量" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="isused" label="已出库数量" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="unused" label="剩余数量" header-align="center" align="center">
                        <template #default="scope">
                            <span v-if="scope.row.unused == 0" class="red bold">0</span>
                            <span v-else>{{ scope.row.unused }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="supplier_name" label="供应商名称" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="operator" label="操作人" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="created_at" label="操作时间" header-align="center" align="center" width="100"></el-table-column>
                </el-table>
                <el-table :data="itemList" border style="width: 100%" width="100%" height="100%" v-if="itemType==2">
                    <el-table-column prop="order_sn" label="出库单号" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="out_time" label="出库时间" header-align="center" align="center" width="100"></el-table-column>
                    <el-table-column prop="out_type" label="出库类型" header-align="center" align="center">
                        <template #default="scope">
                            <span v-if="scope.row.out_type == 1">生产出库</span>
                            <span v-if="scope.row.out_type == 2">销售出库</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="batch_no" label="批次号" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="quantity" label="出库数量" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="customer_name" label="客户名称" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="department_name" label="部门名称" header-align="center" align="center" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="remark" label="出库备注" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="operator" label="操作人" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="created_at" label="操作时间" header-align="center" align="center" width="100"></el-table-column>
                </el-table>
            </el-scrollbar>
           </div>
        </el-dialog>
	</div>
</template>

<script setup lang="ts">
import { useCrud } from '@/hooks'
import { reactive, ref, computed, onMounted } from 'vue'
import { IHooksOptions } from '@/hooks/interface'
import { hasRule } from '@/utils/tool'
import { ElMessageBox } from 'element-plus'
import { addProductSku, exportproduct, getCustomerList, getInventoryItem, getProductTotal, getSupplierList } from '@/api/api'
import { elMsg } from '@/utils/message'
import { SHORTCUTS } from '@/config'
import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';
import { departmentwithuser } from '@/api/org'

const state: IHooksOptions = reactive({
	dataListUrl: '/api/strator/product/inventory',
	queryForm: {
		search: ''
	}
})
const dataList = computed(() => {
    return state.dataList.map(item => {
        return {
            ...item,
            cost_total: (item.inventory*item.cost_price).toFixed(2),
            images: item.images&&item.images!='[]'?item.images.split(','):[],
        }
    })
})
const search = ref({
    id: '',
    name: '',
    attr_name_fill: '',
    attr_name: '',
    start: '',
    end: '',
    customer_name: '',
    supplier_name: '',
    batch_no: '',
    department_name: '',
})
const customerList = ref([])
const departmentList = ref([])
const supplierList = ref([])
const record_time = ref([])
// 选择时间范围
const dataChange = (e: any) => {
	if(e){
		search.value.start = e[0] + ' 00:00:00'
		search.value.end = e[1] + ' 23:59:59'
	}else{
		search.value.start = ''
		search.value.end = ''
	}
}
const totalText = ref('');
const title = ref('');
const totalNum = ref(0);
const totalNumPro = ref(0);
const totalPrice = ref('0.00');
const itemType = ref(1);
const visible = ref(false);
const itemList = ref([]);
// 计算列宽自适应逻辑
const fitToColumn = (data) => {
  const colWidths = [];
  // 遍历表头和数据内容，计算每列最大宽度
  data.forEach(row => {
    Object.values(row).forEach((value, colIndex) => {
      const length = value ? value.toString().length : 0;
      // 中文占双倍宽度（根据字符类型动态调整）
      const chineseMultiplier = /[\u4e00-\u9fa5]/.test(value) ? 2 : 1;
      const cellWidth = Math.ceil(length * chineseMultiplier * 1.2); // 增加 20% 余量
      if (!colWidths[colIndex] || cellWidth > colWidths[colIndex]) {
        colWidths[colIndex] = cellWidth;
      }
    });
  });
  // 转换为 xlsx 的列宽格式
  return colWidths.map(wch => ({ wch }));
};
const exportData = () => {
    exportproduct(state.queryForm).then((result) => {
        const header = JSON.parse(result.data.header);
        console.log(header);
        exportExcel([JSON.parse(result.data.header),...result.data.list], Object.keys(header), result.data.filename)
    }).catch((err) => {
        console.log(err);
    });
}
const exportExcel = (data, header, fileName = 'data.xlsx') => {
  const worksheet = XLSX.utils.json_to_sheet(data, {header:header, skipHeader:true});
  worksheet['!cols'] = fitToColumn(data); // 设置列宽
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
  const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
  saveAs(blob, fileName);
}
const clearForm = () => {
    state.queryForm.search = '';
    getDataLists();
}
const searchHandle = () => {
    handleCheck(search.value,itemType.value);
}
const handleCheck = (row, type, first) => {
    if(first === true){
        record_time.value = [];
        search.value.start = '';
        search.value.end = '';
        search.value.customer_name = '';
        search.value.supplier_name = '';
        search.value.batch_no = '';
        search.value.department_name = '';
    }
    totalNumPro.value = 0;
    search.value.id = row.id;
    search.value.name = row.name;
    search.value.attr_name_fill = row.attr_name_fill;
    search.value.attr_name = row.attr_name;
    itemType.value = type;
    const params = {
        product_id: row.id,
        type: type,
    }
    if(type==1){
        title.value = `${row.name}（${row.attr_name_fill||""}-${row.attr_name}）入库记录`;
        if(search.value.supplier_name){
            params.supplier_name = search.value.supplier_name;
        }
    }else{
        title.value = `${row.name}（${row.attr_name_fill||""}-${row.attr_name}）出库记录`;
        if(search.value.customer_name){
            params.customer_name = search.value.customer_name;
        }
        if(search.value.department_name){
            params.department_name = search.value.department_name;
        }
    }
    if(search.value.start&&search.value.end){
        params.start = search.value.start;
        params.end = search.value.end;
    }
    if(search.value.batch_no){
        params.batch_no = search.value.batch_no;
    }
    itemList.value = [];
    visible.value = true;
    totalText.value = '';
    getInventoryItem(params).then((result) => {
        result.data.forEach(item => {
            if(params.type == 1){
                if(item.isused >= item.quantity){
                    item.isused = item.quantity;
                }
                item.unused = Math.floor(item.quantity - item.isused);
            }
        })
        itemList.value = result.data;
        const tal = result.data.reduce((total, item) => {
            return total + item.quantity;
        }, 0)
        if(type==1){
            totalText.value = `入库总数量：${Math.floor(tal)}`;
        }else{
            totalText.value = `出库总数量：${Math.floor(tal)}`;
        }
        const ttttal = itemList.value.reduce((total,item)=>total+item.quantity, 0);
        totalNumPro.value = Math.ceil(ttttal);
    }).catch((err) => {
        
    });
}
const handleChange = (id) => {
    ElMessageBox.prompt('请输入预警值', '调整预警值', {
        confirmButtonText: '提交',
        cancelButtonText: '关闭',
        inputType: 'number',
    })
        .then(({ value }) => {
            addProductSku({
                id: id,
                warning: Math.floor(value)
            }).then((result) => {
                elMsg('已调整', 'success')
                getDataList();
            }).catch((err) => {
                
            });
        })
        .catch(() => {
        // .
    })
}
const getDataLists = () => {
    getDataList();
    getProductTotals();
}
const getProductTotals = () => {
    getProductTotal({
        search: state.queryForm.search||''
    }).then((result) => {
        console.log(result);
        totalNum.value = Math.ceil(Number(result.data.totalNum));
        totalPrice.value = Number(result.data.totalPrice).toFixed(2);
    }).catch((err) => {
        
    });
}
onMounted(()=>{
    getProductTotals();
    getSupplierList({page:1,per_page:9999}).then((result) => {
        // console.log(result.data.data);
        supplierList.value = result.data.data.map((item) => {
            return {
                ...item,
                label: item.name,
                value: item.name,
            }
        })
    }).catch((err) => {
        
    });
    getCustomerList({page:1,per_page:9999}).then((result) => {
        // console.log(result.data.data);
        customerList.value = result.data.data.map((item) => {
            return {
                ...item,
                label: item.name,
                value: item.name,
            }
        })
    }).catch((err) => {
        
    });
    departmentwithuser({}).then((result) => {
        console.log(result.data);
        departmentList.value = result.data.map((item) => {
            return {
                ...item,
                label: item.department_name,
                value: item.department_name,
            }
        })
    }).catch((err) => {
        
    });
})
const { getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle, deleteHandle } = useCrud(state)
</script>
